package dao

import (
	"fmt"
)

type PostTags []TagData

func GetPostTags(postId int) (tags []TagData) {

	sql := fmt.Sprintf("SELECT `id`,`post_id`,`name` FROM `bg_posts_tags` where post_id=%d ", postId)
	if Db == nil {
		InitMysql()
	}

	rows, err := Db.Query(sql)
	if err != nil {
		LogError(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var tag TagData
		err1 := rows.Scan(&tag.Id, &tag.ContentId, &tag.Name)
		if err1 != nil {
			LogError(err)
			continue
		}
		tags = append(tags, tag)
	}
	return
}

/**
 * 获取标签列表
 * @param orders 排序规则 desc/asc/rand
 * @param limitNum 获取的数量
 */
func GetTagList(orders string, limitNum uint) (tags []TagData) {
	var sql_order = ""
	if orders == "rand" {
		sql_order = "RAND()"
	}

	//不考虑性能的SQL
	sql := fmt.Sprintf("SELECT `id`,`post_id`,`name` FROM `bg_posts_tags` ORDER BY %s LIMIT %d ", sql_order, limitNum)
	if Db == nil {
		InitMysql()
	}

	rows, err := Db.Query(sql)
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var tag TagData
		err1 := rows.Scan(&tag.Id, &tag.ContentId, &tag.Name)
		if err1 != nil {
			LogError(err)
		}
		tags = append(tags, tag)
	}

	return
}

/**
通过标签获取文章ID
*/
func GetPostIdsByTagName(tagName string) (postIds []int64) {
	if Db == nil {
		InitMysql()
	}

	rows, err := Db.Query("select distinct(post_id) as id from `bg_posts_tags` where `name`='" + tagName + "'")
	if err != nil {
		LogError(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var id int64
		rows.Scan(&id)
		postIds = append(postIds, id)
	}

	return
}
